﻿import serial
import math
import os
import serial.tools.list_ports
# from collections import Counter
import random
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# plist = list(serial.tools.list_ports.comports())

milePort = 'com10'
ardPort = 'com11'
filename = "posDis" + str(random.uniform(0,1))

keyData = []
keyDataIndexArr = []
keyDataIndex = 0
startDis = 150

def getData(startDis):
    data = []
    peak = []
    ser = serial.Serial(milePort,115200,timeout=0.5)
    lock = False
    while(True):
        s = str(ser.readline())
        try:
            if s == "b\'Envelope data:\\n\'":
                while(True):
                    s = str(ser.readline())
                    s = s.replace("b\'", "")
                    s = s.replace("\\n\'", "")
                    if s == "end":
                        lock = True
                        break
                    temp = s.split()
                    data.extend(temp)
            if lock:
                dataLen = len(data)
                for p in data:
    	            p = int(p)
    	            peak.append(p)
                distance = [i for i in range(dataLen)]
                distance = np.array(distance) * 0.484 
                # getKeyData(peak, keyData, keyDataIndex, keyDataIndexArr, startDis)
                ser.close()
                return distance, peak
        except ValueError:
                print("Test again!")
                ser.close()
                break

def plotData(xData, yData, title, xlabel, ylabel, subplotPos):
    plt.subplot(subplotPos)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.plot(xData, yData)

def getKeyData(peak, keyData, keyDataIndex, keyDataIndexArr, startDis):
    #输出最值并用文档记录
    keyDistance = peak.index(max(peak)) * 0.484 + startDis
    print(keyDistance)
    dataString = str(max(peak)) + '\t' + str(keyDistance) + '\t'

    with open(filename,"a") as f:
        f.write(dataString)

    if keyDataIndex > 10:
        keyData.pop(0)
        keyData.append(keyDistance)
        keyDataIndexArr.pop(0)
        keyDataIndexArr.append(keyDataIndex)
    else:
        keyData.append(keyDistance)
        keyDataIndexArr.append(keyDataIndex)

def plotResult():
    plt.clf()
    plotData(distance, peak, 'envelope', 'Distance(mm)', 'Peak', 211)
    plotData(keyDataIndexArr, keyData, 'maxPeakDistance', 'testIndex(n)', 'Distance', 212)
    plt.draw()
    plt.pause(0.1)
    plt.ioff()

while True:
    ser2=serial.Serial('com11',115200,timeout=0.5)
    s1 = str(ser2.readline())
    print(s1)
    ser2.close()
#     if len(s1) == 6:
#         ser2.close()
#         keyDataIndex = keyDataIndex + 1
#         getData(startDis)
#         
#     plt.ion()
#     plotResult()
#     plt.ioff()

# pos = np.arange(10)
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# for z in pos:
#     print(z)
#     distance, peak = getData(milePort)
#     # 数据下采样
#     distance = distance[::10]
#     peak = peak[::10]
#     ax.bar(distance, peak, zs=z, zdir='y')
 
# ax.set_xlabel('distance')
# ax.set_ylabel('position')
# ax.set_zlabel('peak')
 
# plt.show()